
# import tensorflow as tf
# from .conf import model_path
# import numpy as np
#
# model = tf.keras.models.load_model(model_path)
#
# class_names = ['圣女果', '梨', '芒果', '苹果', '香蕉']
#
#
# def load_and_preprocess_image(path):
#     image = tf.io.read_file(path)
#     image = tf.image.decode_jpeg(image, channels=3)
#     image = tf.image.resize(image, [224, 224])
#     image = tf.cast(image, tf.float32)
#     image = image / 255.0  # normalize to [0,1] range
#     return image
#
#
# def check_handle(img_path):
#     test_img = img_path
#     test_tensor = load_and_preprocess_image(test_img)
#     test_tensor = tf.expand_dims(test_tensor, axis=0)
#     pred = model.predict(test_tensor)
#     pred_num = np.argmax(pred)
#     result = class_names[int(pred_num)]
#     return result


import json
import os

import cv2

import numpy as np
from PIL import Image
from ultralytics import YOLO

class predict:
    def __init__(self):
        self.model = YOLO("../pt/best.pt")

    def get_image_size(self, image_path):
        image_name = os.path.basename(image_path)
        with Image.open(image_path) as img:
            width, height = img.size
        return image_name, width, height

    def detect_image(self, image_path):
        print(image_path)
        # Perform prediction
        results = self.model.predict(source=image_path, show=False, save=False)
        im0=results[0].plot()
        cv2.imwrite('media/image/mip_image.jpg', im0)
        box=results[0].boxes.cpu()
        #获取目标框的信息
        conf = box.conf

        # if conf==0:
        #     conf=1
        # else :
        #     conf=0

        clas=box.cls.numpy()
        # for i,a in np.ndenumerate(clas):
        #     if a==0:
        #         clas[i]=1
        #     else:
        #         clas[i]=0

        boxes = box.xyxy.numpy()[:, [1, 0, 3, 2]].astype(int)
        #print("boxes:",boxes)
        boxes = np.hstack((boxes, conf.reshape(-1, 1)))
        boxes = np.hstack((boxes, clas.reshape(-1, 1)))

        # 按照 ymin 升序排序
        boxes = sorted(boxes, key=lambda x: x[0])  # x[0] 表示 ymin
        boxes = np.array(boxes)
        result = []

        # 转换并写入新的结果文件
        for row in boxes:
            result.append(list(row))


        return result


# import os
# from flask import Flask, request
#
# app = Flask(__name__)
# from flask import jsonify
# from werkzeug.utils import secure_filename
#
# # 上传的图片保存路径
# UPLOAD_PATH = os.path.join(os.path.dirname(__file__), 'images')
# UPLOAD_FOLDER = 'E:\danzi'  # 替换为你的上传文件夹路径
# app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#
# @app.route('/upload', methods=['GET','POST'])
# def upload_pic():
#     # 来获取多个上传文件
#     # imgs = request.files.get("file_imgs")
#     file = request.files['file_img']
#     filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
#
#     file.save(filename)
#     filename_with_backslash = filename.replace('\\', '/')
#     return_dict = {'return_code': '200', 'return_info': '处理成功', 'result': False}
#     result = train(filename_with_backslash)
#     # 84行返回就报错
#     print(result)
#     return jsonify(result)
#     # return json.dumps(return_dict, ensure_ascii=False)



# def train(img):
#     model=predict()
#     results=model.detect_image(img)
#     print(results)
#     return results



def check_handle(img_path):
    model = predict()
    results = model.detect_image(img_path)

    if results == []:
        return "检测失败"
    if int(results[0][5]) == 11 or  int(results[0][5]) == 10:
            result = "苹果"
            print("苹果")
            return result

    if int(results[0][5]) == 0 or  int(results[0][5]) == 1:
            print("banana")
            result = "香蕉"
            return result

    if int(results[0][5]) == 2 :
            print("blackberries")
            result = "黑桑葚"
            return result

    if int(results[0][5]) == 3 :
            print("raspberry")
            result = "树莓"
            return result

    if int(results[0][5]) == 4 or  int(results[0][5]) == 5:
            print("lemon")
            result = "柠檬"
            return result

    if int(results[0][5]) == 6 or  int(results[0][5]) == 7:
            print("grapes")
            result = "葡萄"
            return result

    if int(results[0][5]) == 8 or  int(results[0][5]) == 9:
            print("tomato")
            result = "西红柿"
            return result

    if int(results[0][5]) == 12 or  int(results[0][5]) == 13:
            print("chilli")
            result = "辣椒"
            return result

# if __name__ == '__main__':
#
#     image_path='test_images/apple.jpg'
#     model=predict()
#     results=model.detect_image(image_path)
#     if int(results[0][5]) == 11 or  int(results[0][5]) == 10:
#         print("apple")
#     if int(results[0][5]) == 0 or  int(results[0][5]) == 1:
#         print("banana")
#     if int(results[0][5]) == 2 :
#         print("blackberries")
#     if int(results[0][5]) == 3 :
#         print("raspberry")
#     if int(results[0][5]) == 4 or  int(results[0][5]) == 5:
#         print("lemon")
#     if int(results[0][5]) == 6 or  int(results[0][5]) == 7:
#         print("grapes")
#     if int(results[0][5]) == 8 or  int(results[0][5]) == 9:
#         print("tomato")
#     if int(results[0][5]) == 12 or  int(results[0][5]) == 10:
#         print("chilli")
#     print(results)
